package com.ptkc.ext;

import com.alibaba.fastjson.JSON;
import com.ptkc.core.canal.handler.EventTypeHandler;
import com.ptkc.core.esearch.model.Business;
import com.ptkc.core.esearch.model.Order;
import com.ptkc.core.esearch.repos.BusinessRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月28日
 */
@Component
@Slf4j
public class BusinessCanalSyncHandler extends EventTypeHandler<Business> {

    @Autowired
    private BusinessRepository businessRepository;

    public BusinessCanalSyncHandler() {
        super("runfast", "runfast_business");
    }

    @Override
    public Class<? extends Business> getEntryClass() {
        return Business.class;
    }

    @Override
    public boolean getSubscribe(String database, String table) {
        return this.getDatabase().equalsIgnoreCase(database) && this.getTable().equalsIgnoreCase(table);
    }

    @Override
    public void onInsert(Business rowData) {
        if(rowData != null && rowData.getId() != null) {
            try {
                businessRepository.save(rowData);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("记录商家信息失败:{},{}", JSON.toJSONString(rowData), e.getCause());
            }
        }
    }

    @Override
    public void onUpdate(Business rowData) {
        this.onInsert(rowData);
    }

    @Override
    public void onDelete(Business rowData) {
        try {
            businessRepository.del(String.valueOf(rowData.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除商家信息失败:{},{}", JSON.toJSONString(rowData), e.getCause());
        }
    }
}
